package com.corecmd.tcloud.tcim.common;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;

import com.corecmd.tcloud.tcim.R;


public class RoundCornerButton extends AppCompatButton {

    private int colorNormal;
    private int colorPress;
    private float cornerRadius;
    private RoundCornerDrawable bgDrawableNormal = null;
    private RoundCornerDrawable bgDrawablePress = null;

    public RoundCornerButton(@NonNull Context context) {
        super(context);
        initCornerBackground(null,0);
    }

    public RoundCornerButton(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initCornerBackground(attrs,0);
    }

    public RoundCornerButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCornerBackground(attrs,defStyleAttr);
    }

    // 构造方法最后一定要调用initCornerBackground完成初始化

    private void initCornerBackground(AttributeSet attrs, int defStyleAttr) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RoundCornerButton, defStyleAttr, 0);

        this.cornerRadius = a.getDimension(R.styleable.RoundCornerButton_rcb_cornerRadius, 0);
        this.colorNormal = a.getColor(R.styleable.RoundCornerButton_rcb_backgroundColor, 0);
        this.colorPress = a.getColor(R.styleable.RoundCornerButton_rcb_backgroundColorPress, 0);
        makeBackgroundDrawable();

        a.recycle();
    }

    private void makeBackgroundDrawable() {
        bgDrawableNormal = new RoundCornerDrawable(this.colorNormal, this.cornerRadius);
        bgDrawableNormal.setRect(getWidth(), getHeight());

        bgDrawablePress = new RoundCornerDrawable(this.colorPress, this.cornerRadius);
        bgDrawablePress.setRect(getWidth(), getHeight());

        // 设计通常会给出禁用时的样式以及按下时的样式
        // 所以这里用使用StateListDrawable
        StateListDrawable bgDrawable = new StateListDrawable();
        bgDrawable.addState(new int[]{android.R.attr.state_enabled}, bgDrawableNormal);
        bgDrawable.addState(new int[]{android.R.attr.state_pressed}, bgDrawablePress);
        // 每多一种状态，在这里多加一项
        setBackgroundDrawable(bgDrawable);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        // layout之后必然会draw，所以在这里设置drawable的尺寸
        if (bgDrawableNormal != null) {
            bgDrawableNormal.setRect(right - left, bottom - top);
        }

        if (bgDrawablePress != null) {
            bgDrawablePress.setRect(right - left, bottom - top);
        }
        // 每多一种状态，在这里多加一项
    }
}
